<!--
* 功能-页面实现
* Date: 2023-9-12
* Author: 刘浩
 -->
<template>
  <layout-card
    class="layoutCard"
    v-model="search"
    headline="施工项目数据"
    :hasButton="true"
    :buttonFilters="buttonOptions"
    @search-change="getData"
    @search-reset="searchReset"
  >
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="listCard" style="background-color: #e7fcfd">
          <div>全部</div>
          <div>{{ projectTypeNum.allNum || 0 }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="listCard" style="background-color: #f2fce0">
          <div>已立项项目</div>
          <div>{{ projectTypeNum.approvedNum || 0 }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="listCard" style="background-color: #fffce2">
          <div>临时施工</div>
          <div>{{ projectTypeNum.temporaryNum || 0 }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="listCard" style="background-color: #f4e8ff">
          <div>维修施工</div>
          <div>{{ projectTypeNum.maintenanceNum || 0 }}</div>
        </div>
      </el-col>
    </el-row>
    <!-- :loading="loading" -->
    <div class="container">
      <div class="tBody">
        <table-scroll
          :disabled="disabled"
          class="scroll-table"
          :columns="TopColumns"
          :pagination="pager"
          :table-data="topTable"
          size="normal"
          :height="220"
          @current-change="changeCurrent"
          @size-change="changePageSize"
          @sort-change="handleSortChange"
          @scroll="scroll"
        >
        <template #projectType="{ row }">
            <!-- 提示：此处状态值根据具体业务来处理，此处仅做自定义列示例  -->
            <el-text v-if=" row['projectType'] ==='1'">已立项项目</el-text>
            <el-text v-else-if=" row['projectType'] ==='2'">临时施工</el-text>
            <el-text v-else-if=" row['projectType'] ==='3'">维修施工</el-text>
          </template>
          <template #action="{ row }">
            <!-- 提示：此处状态值根据具体业务来处理，此处仅做自定义列示例  -->
            <el-text
              type="danger"
              v-if=" !row['actualEndTime'] && dayjs().format('YYYY-MM-DD HH:mm:ss') > row['planEndTime']"
              >延期</el-text
            >
            <el-text
              type="danger"
              v-else-if="
                row['actualEndTime'] &&
                row['actualEndTime'] > row['planEndTime']
              "
              >延期</el-text
            >
            <el-text
              type="success"
              v-else
              >正常</el-text
            >
          </template>
          <template #state="{ row }">
            <!-- 提示：此处状态值根据具体业务来处理，此处仅做自定义列示例  -->
            <el-text type="danger" v-if=" row['state'] ==='1'">已驳回</el-text>
            <el-text v-else-if=" row['state'] ==='2'">待审批</el-text>
            <el-text v-else-if=" row['state'] ==='3'">待培训</el-text>
            <el-text v-else-if=" row['state'] ==='4'">待收押金</el-text>
            <el-text v-else-if=" row['state'] ==='6'">待安全评估</el-text>
            <el-text v-else-if=" row['state'] ==='7'">待开工</el-text>
            <el-text v-else-if=" row['state'] ==='8'">施工中</el-text>
            <el-text v-else-if=" row['state'] ==='9'">待延期</el-text>
            <el-text v-else-if=" row['state'] ==='10'">待验收</el-text>
            <el-text v-else-if=" row['state'] ==='11'">待退押金</el-text>
            <el-text v-else-if=" row['state'] ==='12'">已退场</el-text>
            <el-text v-else-if=" row['state'] ==='13'">即将延期</el-text>
            <el-text v-else-if=" row['state'] ==='14'">已延期</el-text>
          </template>
        </table-scroll>
      </div>
    </div>
  </layout-card>
  <layout-card
    class="layoutCard"
    v-model="search"
    headline="每日施工申请数据"
    :hasButton="true"
    @search-change="getData"
    @search-reset="searchReset"
  >
    <el-row :gutter="20">
      <el-col :span="5">
        <div class="listCard" style="background-color: #e7fcfd">
          <div>全部</div>
          <div>{{ dailyApplayNum.allNum || 0 }}</div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="listCard" style="background-color: #f2fce0">
          <div>已立项项目</div>
          <div>{{ dailyApplayNum.approvedNum || 0 }}</div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="listCard" style="background-color: #fffce2">
          <div>临时施工</div>
          <div>{{ dailyApplayNum.temporaryNum || 0 }}</div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="listCard" style="background-color: #f4e8ff">
          <div>维修施工</div>
          <div>{{ dailyApplayNum.maintenanceNum || 0 }}</div>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="listCard" style="background-color: #ffe6eb">
          <div>应急施工</div>
          <div>{{ dailyApplayNum.emergencyNum || 0 }}</div>
        </div>
      </el-col>
    </el-row>

    <table-common

      :columns="BottomColumns"
      :pagination="isShowPagin"
      :height="220"
      :table-data="bottomTable"
      size="large"
      @current-change="changeCurrent"
      @size-change="changePageSize"
      @sort-change="handleSortChange2"
    >

      <!-- 提示：需要格式化显示内容的字段值根据实际情况修改，此处示例使用的是area  -->
      <template #area="{ row }">
        <el-popover
          placement="bottom"
          :width="260"
          trigger="click"
          content="若需进入隔离区，则请办理相关证件!"
          v-if="row['area'] === '隔离区'"
        >
          <template #reference>
            <el-text type="primary">
              <el-icon>
                <Warning />
              </el-icon>
            </el-text>
          </template>
        </el-popover>
        {{ row['area'] }}
      </template>
      <template #projectType="{row}">
        <el-text v-if=" row['projectType'] ==='1'">已立项项目</el-text>
        <el-text v-else-if=" row['projectType'] ==='2'">临时施工</el-text>
        <el-text v-else-if=" row['projectType'] ==='3'">维修施工</el-text>
        <el-text v-else>应急施工</el-text>
      </template>
      <!-- 提示：需要格式化显示内容的字段值根据实际情况修改，此处示例使用的是state  -->
      <template #state="{ row }">
        <!-- 提示：此处状态值根据具体业务来处理，此处仅做自定义列示例  -->
        <el-text v-if="row['state'] === '1'">待审批</el-text>
        <el-text v-else-if="row['state'] === '2'">已驳回</el-text>
        <el-text type="danger" v-else-if="row['state'] === '3'">已通过</el-text>
      </template>
      <template #process="{ row }">
        <!-- 提示：此处状态值根据具体业务来处理，此处仅做自定义列示例  -->
        <el-text type="success" v-if="row['process'] === '1'"
          >已完成（10/10）</el-text
        >
        <el-text type="warning" v-else-if="row['process'] === '2'"
          >执行中（2/20）</el-text
        >
        <el-text type="danger" v-else-if="row['process'] === '3'"
          >未开始 （0/20）</el-text
        >
      </template>
    </table-common>
  </layout-card>
  <edit-dialog
    :centerDialogVisible="centerDialogVisible"
    :tilte="addTilte"
    :key="timer"
    @Cancel="Cancel"
    @Submit="Submit"
  >
    <template #content>
      <layout-card v-model="search" :filters="dialogType" :hasButton="false" />
    </template>
  </edit-dialog>
</template>

<script lang="ts" setup>
import { computed, ref, onBeforeMount, onUnmounted,onMounted, reactive } from 'vue'
// 7-18修改LayoutCard 页面，hasButton参数为false时显示为弹窗样式，为true时显示为搜索栏样式
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import TableScroll from '@/components/TableScroll/index.vue'
import { TopColumns, BottomColumns } from './config/columns'
import {
  buttonOptions,
  demoOptions,
  dialogOptions,
  dialogEditOptions
} from '@/views/Demo/config/filters'
import { usePagination } from 'vue-request'
import { dayjs } from 'element-plus'
import {
  loadProjectData,
  loadProjectCountData,
  loadDailyApplayData,
  loadDailyApplayCountData
} from '@/api/monitor/construction'
import editDialog from '@/components/editDialog/index.vue'
// =============模拟接口数据-START
// 此处是模拟的接口返回数据，项目中请用`@/api/`下接口代替，删除当前代码！
const Service = (data: ListParams) => {
  return new Promise((resolve) => {
    // 模拟数据写入，实际开发使用接口数据写入
    // area1 这个值仅用于判断演示，根据实际情况进行编写
  })
}
// =============模拟接口数据==END

const currentNum = ref(1)
const pageSizeNum = ref(5)
const disabled = ref(false)
/**
 * 取消下面分页
 */
const isShowPagin = ref(null)
/**
 * 上面表格数据
 */
const topTable = ref([])
/**
 * 下面表格数据
 */

const bottomTable = ref([])
const {
  run,
  data,
  loading,
  current,
  pageSize,
  total,
  changeCurrent,
  changePageSize
} = usePagination(Service, {
  manual: true,
  pagination: {
    currentKey: 'pageNum',
    pageSizeKey: 'pageSize',
    totalKey: 'data.total'
  }
})
const testOptions = ref([
  { label: '全部', value: 1 },
  { label: '安检通道告警', value: 2 },
  { label: '登机口告警', value: 3, num: 12 },
  { label: '值机通道告警', value: 4 },
  { label: '人流密度告警', value: 5, num: 3 }
])

// 7-21新增用于保存下拉列表选择数据
const value = ref<string[]>([])
const radioValue = ref()
// 新增弹窗是否打开
const centerDialogVisible = ref(false)
// 弹窗标题
const addTilte = ref('新增问题类型')
// 弹窗页面类型
const dialogType = ref()
// 时间戳，用于确保弹窗页面能加载不同的界面
const timer = ref()
// const visible = ref(false)
// const isAdd = ref(true)
// const handleCreate = () => {
//   isAdd.value = true
//   visible.value = true
// }
// 7-17------------------
// 打开新增窗口
// 新增窗口点击取消
// 7-17------------------
const pager = computed(() => ({
  currentPage: currentNum.value,
  pageSize: pageSizeNum.value,
  total: total.value,
  // 7-24 手动设置了总页数
  pageCount: Math.ceil(total.value / pageSize.value)
}))

// 查询的排序参数
const search = ref<FilterDataType>({ order: [{}] })
// 由于当前页面有两个表格 所以search2是下面的参数
const search2 = ref<FilterDataType>({ order: [{}] })

// 接收施工项目数据项目类型状态熟练的变量
const projectTypeNum = ref({})

// 接收每日施工申请数据不同状态的变量
const dailyApplayNum = ref({})

/**
 * @param column 当前列
 */
const handleSortChange = (column: any) => {
  const prop = column.prop
  let order = column.order
  if (order === 'descending') {
    order = 'DESC'
  } else if (order === 'ascending') {
    order = 'ASC'
  }

  params1.pageSize=currentNum.value*pageSizeNum.value
  params1.condition.order = [ {
        column: prop,
        method: order
      }]
  // search.value = {
  //   order: [
  //     {
  //       column: prop,
  //       method: order
  //     }
  //   ]
  // }
  getData()
  // loadProjectData(search.value)
}
const handleSortChange2 = (column: any) => {
  const prop = column.prop
  let order = column.order
  if (order === 'descending') {
    order = 'DESC'
  } else if (order === 'ascending') {
    order = 'ASC'
  }
  // params2 = {
  //   order: [
  //     {
  //       column: prop,
  //       method: order
  //     }
  //   ]
  // }
  params2.order =[
    {
      column:prop,
      method:order
    }
  ]
  getData()
}

// 查询参数
const params1 = {
  pageNum: currentNum.value,
  pageSize: pageSizeNum.value,
  condition: {
    order:[{
      column:'',
      method:''
  }]
  }

}
const params2 = {
  order:[
    {
      column:'state',
      method:'DESC'
    }
  ]
}

// 获取数据
const getData = () => {
  loadProjectData(params1).then((res) => {
    topTable.value = res.data.list
    params1.pageNum=1
    params1.pageSize=5
  })
  loadDailyApplayData(params2).then((res) => {
    bottomTable.value = res.data
  })
  loadProjectCountData().then((res) => {
    projectTypeNum.value.allNum = res.data.allNumber
    res.data.projectRecordList.forEach((p: any) => {
      if (p.projectType === '1') {
        projectTypeNum.value.approvedNum = p.number
      } else if (p.projectType === '2') {
        projectTypeNum.value.temporaryNum = p.number
      } else if (p.projectType === '3') {
        projectTypeNum.value.maintenanceNum = p.number
      }
    })
  })
  loadDailyApplayCountData().then((res) => {
    dailyApplayNum.value.allNum = res.data.allNumber
    dailyApplayNum.value.emergencyNum = res.data.tempProject.number
    res.data.projectRecordList.forEach((p: any) => {
      if (p.projectType === '1') {
        dailyApplayNum.value.approvedNum = p.number
      } else if (p.projectType === '2') {
        dailyApplayNum.value.temporaryNum = p.number
      } else if (p.projectType === '3') {
        dailyApplayNum.value.maintenanceNum = p.number
      }
    })
  })

  // run(params);
}

const getDataTimer = setInterval(() => {
  disabled.value = false
  params1.pageNum = 1
  currentNum.value=1
  getData()
}, 30000)


onBeforeMount(getData)
onUnmounted(() => {
  clearInterval(getDataTimer)
})

/**
 * 滚动分页的组件
 *
 */
const scroll = () => {
  loading.value = true
  currentNum.value += 1
  setTimeout(() => {
    getScrollData()
  }, 300)
}
const getScrollData = async () => {
  let page = {
    current: currentNum.value,
    size: pageSizeNum.value
  }
  // 此处应该是获取接口数据
  loading.value = false
  // 把每一次滚动加载请求的数据push的routeData数组
  params1.pageNum = page.current
  params1.pageSize = page.size
  let toplist = []
  const topRes = await loadProjectData(params1)

  toplist = topRes.data.list
  // 当无法再获取数据或者数据量大于999条时，停止滚动
  if (
    topTable.value.length >= projectTypeNum.value.allNum ||
    topTable.value.length >= 999
  ) {
    disabled.value = true
  } else {
    for (let i = 0; i < toplist.length; i++) {
      topTable.value.push(toplist[i])
    }
    disabled.value = false
  }
  loading.value = false
}
</script>
<style scoped lang="less">
.container {
  background: #f5f7f9;
  overflow: hidden;
}

.container .card-content {
  padding: 10px;
  margin: 0;
  background: #fff;
  border-radius: 8px;
}

.listCard {
  margin-right: 20px;
  box-sizing: border-box;
  padding: 10px 20px;
  min-width: 60px;
  height: 80px;
  color: black;
  font-size: 28px !important;
  font-weight: 400 !important;
  margin-bottom: 20px;
  border-radius: 8px;
}

.listCard div:nth-child(1) {
  font-size: 12px;
}
.container {
  width: 100%;
  height: 100%;
  padding: 0;
  background-color: #ffffff;
}
.layoutCard{
  position: relative;
  /deep/ .card-content{
    margin: 0;
  }
}
.tBody {
  float: left;
  width: 100%;
  height: auto;
  margin: 10px;
  padding: 10px;
  background-color: #fff;
  overflow-y: auto;
}
.scroll-table {
  height: 200px;
}
</style>
